package com.zackeus.xupdate;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;

import androidx.annotation.NonNull;

import com.zackeus.common.utils.CollectionUtils;
import com.zackeus.common.utils.ObjectUtils;
import com.zackeus.xupdate.constant.Error;
import com.zackeus.xupdate.entity.LibraryUpdateEntity;
import com.zackeus.xupdate.entity.PromptEntity;
import com.zackeus.xupdate.entity.UpdateError;
import com.zackeus.xupdate.factory.IUpdateDownloader;
import com.zackeus.xupdate.factory.IUpdateFactory;
import com.zackeus.xupdate.factory.IUpdateProxy;
import com.zackeus.xupdate.factory.impl.DefaultUpdateChecker;
import com.zackeus.xupdate.factory.IUpdateChecker;
import com.zackeus.xupdate.widget.BaseUpdateActivity;
import com.zackeus.xupdate.widget.DefaultUpdateActivity;

import java.lang.ref.WeakReference;
import java.util.Map;
import java.util.TreeMap;

/**
 * APP 版本更新
 * @name: XUpdateApp
 * @author: zz
 * @date: 2022/11/17
 */
public class XUpdateApp implements IUpdateProxy {

    private static final String LOG_TAG = XUpdateApp.class.getSimpleName();

    //=======必填项========//
    private final WeakReference<Context> mContext;

    //===========更新模式================//
    /* 是否只在wifi下进行版本更新检查 */
    private final boolean mWifiOnly;

    //===========更新行为================//
    /* 构建工厂 */
    private final IUpdateFactory mFactory;
    /* 检查器 */
    private final IUpdateChecker mChecker;
    /* 提示器 */
    private final Class<? extends BaseUpdateActivity<? extends IUpdateDownloader>> mPrompter;

    private XUpdateApp(@NonNull Builder builder) {
        this.mContext = new WeakReference<>(builder.context);
        this.mWifiOnly = builder.wifiOnly;
        this.mFactory = builder.factory;
        this.mChecker = builder.checker;
        this.mPrompter = builder.prompter;
    }

    @NonNull
    @Override
    public Context getContext() {
        return this.mContext.get();
    }

    @Override
    public boolean isWifiOnly() {
        return this.mWifiOnly;
    }

    public void update() {
        this.update(new TreeMap<>());
    }

    @Override
    public void update(@NonNull Map<String, Object> params) {
        if (CollectionUtils.isNotEmpty(XUpdate.with().params())) {
            params.putAll(XUpdate.with().params());
        }

        if (ObjectUtils.isNull(this.mFactory)) {
            XUpdate.with().onUpdateError(new UpdateError(Error.UPDATE_UNKNOWN, "the IUpdateFactory interface not implemented"));
            return;
        }

        this.mFactory.newUpdate(params, new IUpdateFactory.Callback() {
            @Override
            public void onSuccess(LibraryUpdateEntity entity) {
                XUpdateApp.this.update(entity);
            }

            @Override
            public void onError(Throwable throwable) {
                XUpdate.with().onUpdateError(new UpdateError(Error.UPDATE_UNKNOWN, throwable));
            }
        });
    }

    /**
     * 版本更新操作
     */
    @Override
    public void update(@NonNull LibraryUpdateEntity entity) {
        if (this.mChecker.checkVersion(entity, mWifiOnly)) {
            /* 更新弹窗 */
            Intent intent = new Intent(this.getContext(), this.mPrompter);
            if (!(this.getContext() instanceof Activity)) {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            }
            // TODO: 2022/12/8 优化弹窗参数设置
            BaseUpdateActivity.initIntent(intent, entity, new PromptEntity());
            this.getContext().startActivity(intent);
        }
    }

    @Override
    public void recycle() {}

    /**
     * 版本更新构建器
     */
    public static final class Builder {
        //=======必填项========//
        private final Context context;

        //===========更新模式================//

        /* 是否只在wifi下进行版本更新检查 */
        private boolean wifiOnly;

        //===========更新行为================//
        /* 构建工厂 */
        private IUpdateFactory factory;
        /* 检查器 */
        private IUpdateChecker checker;
        /* 提示器类 */
        private Class<? extends BaseUpdateActivity<? extends IUpdateDownloader>> prompter;

        public Builder(@NonNull Context context) {
            this.context = context;

            this.wifiOnly = Boolean.TRUE;

            this.checker = new DefaultUpdateChecker();
            this.prompter = DefaultUpdateActivity.class;
        }

        /**
         * 设置是否只在wifi下进行版本更新检查
         * @param wifiOnly
         * @return
         */
        @NonNull
        public XUpdateApp.Builder wifiOnly(boolean wifiOnly) {
            this.wifiOnly = wifiOnly;
            return this;
        }

        /**
         * 自定义检查器
         * @param c
         * @return
         */
        @NonNull
        public XUpdateApp.Builder checker(IUpdateChecker c) {
            this.checker = c;
            return this;
        }

        @NonNull
        public XUpdateApp.Builder factory(IUpdateFactory factory) {
            this.factory = factory;
            return this;
        }

        /**
         * 自定义版本更新弹窗页面
         * @param p
         * @return
         */
        @NonNull
        public XUpdateApp.Builder prompter(Class<? extends BaseUpdateActivity<? extends IUpdateDownloader>> p) {
            this.prompter = p;
            return this;
        }

        public XUpdateApp build() {
            return new XUpdateApp(this);
        }
    }
}
